#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "InetAddr.hpp"
#include "socket.hpp"
#include <functional>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <cstring>
#include "Log.hpp"

using namespace socket_ns;
class TcpServer;
// 线程池的任务队列参数类型
using task_t = std::function<void()>;
using http_service_t = std::function<std::string(std::string req)>;
// 数据类型，用于传入线程函数
class ThreadData
{
public:
    ThreadData(socket_ptr &sockfd, InetAddr &client_addr, TcpServer *s)
        : _sockfd(sockfd), _client_addr(client_addr), _self(s)
    {
    }

public:
    socket_ptr _sockfd;
    InetAddr _client_addr;
    TcpServer *_self;
};
// 服务器
class TcpServer
{
public:
    TcpServer(uint16_t port, http_service_t service)
        : _localaddr("0", port), _http_service(service), _listen_socket(std::make_shared<TcpSocket>()),
          _is_running(false)
    {
        std::cout << "Tcpserver()" << std::endl;
        // 创建listen_socket
        _listen_socket->BuildServerSocket(_localaddr);
    }
    static void *Handelersock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);

        // 线程分离
        // 将sockfd，client套接字传入service函数
        std::string request,response;
        int n = td->_sockfd->Recv(&request);
        if (n > 0)
        {
            response=td->_self->_http_service(request);
            //std::cout<<"HandelerSock:"<<response<<std::endl;
            td->_sockfd->Send(response);
        }

        close(td->_sockfd->SockFd());
        delete td;
        return nullptr;
    }
    void start()
    {
        _is_running = true;
        // 服务器正在运行
        while (_is_running)
        {
            // 创建连接的sockfd
            InetAddr clientaddr;
            socket_ptr sockfd = _listen_socket->AcceptSocket(&clientaddr);
            // 采用多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(sockfd, clientaddr, this);
            pthread_create(&tid, nullptr, Handelersock, td);
        }
        // 服务器终止
        _is_running = false;
    }
    ~TcpServer() {}

private:
    InetAddr _localaddr;          // 本机套接字结构体，与listen_sockfd进行绑定
    http_service_t _http_service; // 执行服务器服务的函数

    bool _is_running;                       // 服务器运行状态
    std::shared_ptr<Socket> _listen_socket; // listensocket
};